package cn.sylinx.common.ext.xml;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import cn.sylinx.common.ext.log.GLog;

/**
 * 通用方法，用于转换xml到bean，或者bean 到xml
 * 
 * @author han
 *
 */
public class JacksonUtils {

	/**
	 * XML To Object
	 *
	 * @param xmlPath
	 * @param cls
	 * @param <T>
	 * @return
	 * @throws IOException
	 */
	public static <T> T xmlToBean(String xmlPath, Class<T> cls) {
		XmlMapper xml = JacksonMapper.getXmlMapper();
		T obj = null;
		try {
			obj = xml.readValue(new File(xmlPath), cls);
		} catch (Exception e) {
			GLog.error("xmlToBean error: ", e);
		}
		return obj;
	}

	/**
	 * @param xmlFile
	 * @param cls
	 * @param <T>
	 * @return
	 * @throws IOException
	 */
	public static <T> T xmlToBean(File xmlFile, Class<T> cls) {
		XmlMapper xml = JacksonMapper.getXmlMapper();
		T obj = null;
		try {
			obj = xml.readValue(xmlFile, cls);
		} catch (Exception e) {
			GLog.error("xmlToBean error: ", e);
		}
		return obj;
	}

	/**
	 * @param xmlInputStream
	 * @param cls
	 * @param <T>
	 * @return
	 * @throws IOException
	 */
	public static <T> T xmlToBean(InputStream xmlInputStream, Class<T> cls) {
		XmlMapper xml = JacksonMapper.getXmlMapper();
		T obj = null;
		try {
			obj = xml.readValue(xmlInputStream, cls);
		} catch (Exception e) {
			GLog.error("xmlToBean error: ", e);
		}
		return obj;
	}

	public static <T> String beanToXml(T bean) {
		XmlMapper xml = JacksonMapper.getXmlMapper();
		String string = null;
		try {
			string = xml.writeValueAsString(bean);
		} catch (JsonProcessingException e) {
			GLog.error("beanToXml error: ", e);
		}
		return string;
	}
}
